package com.kitty.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ValidCode extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -7367895384839774400L;
	//设置字母的大小
	private static final Font FONT = new Font("Comic Sans MS", Font.PLAIN, 20);
	private static final int CODE_LENGTH = 4;
	// 图片的高度宽度
	private static final int WIDTH = 70;
	private static final int HEIGHT = 25;

	/**
	 * Constructor of the object.
	 */
	public ValidCode() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy();
	}
	
	
	@SuppressWarnings("static-access")
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		OutputStream out = response.getOutputStream();
		response.setContentType("image/jpeg");
		response.setHeader("Pragma","No-cache");
		response.setHeader("Cache-Control","no-cache");
		response.setDateHeader("Expires", 0);
		
		BufferedImage image = new BufferedImage(this.WIDTH, this.HEIGHT,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		
		g.setColor(Color.WHITE);
		g.setFont(this.FONT);
		g.fillRect(0, 0, this.WIDTH, this.HEIGHT);
		
		String sRand = new StringUtil().getRandomString(CODE_LENGTH);
		g.setColor(Color.BLUE);
		for (int i = 0; i < CODE_LENGTH; i++) {
			String rand = sRand.substring(i, i + 1);
			
			g.drawString(rand, 15 * i + 4, 18);
		}
		request.getSession().setAttribute("validcode", sRand);
		g.dispose();
		ImageIO.write(image, "JPEG", out);
		
		out.flush();
		out.close();
		out = null;
		image = null;
		g = null;
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		super.init();
	}

}
